package com.android.meige.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.meige.model.group.MainList;
import com.android.meige.R;
import com.android.meige.activity.mine.LoginActivity;
import com.android.meige.adapt.MainlistAdapt;
import com.android.meige.app.BaseActivity;
import com.android.meige.model.data;
import com.android.meige.model.dataCallback;
import com.android.meige.model.detail.StoreGood;
import com.android.meige.model.detail.StoreGoodCallback;
import com.android.meige.model.detail.StoreMessage;
import com.android.meige.model.detail.StoreMessageCallback;
import com.android.meige.utils.ConstantsUrl;
import com.android.meige.utils.HttpUtils;
import com.android.meige.utils.LoginState;
import com.android.meige.utils.MyLog;
import com.android.meige.utils.ObjectUtils;
import com.android.meige.view.recycleview.CustomLoadMoreView;
import com.android.meige.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class GoodsStoreActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;
    private GoodsStoreActivity mcontext;
    private String storeid;
    private boolean networkConnected;
    private MainlistAdapt adapter;

    private int page = 1;
    private List<StoreMessage.DataBean.CouponBean> tj_list = new ArrayList<>();
    private View head;
    private NestFullListView list_coupon;
    private TextView store_collect;
    private int goods_id;
    private String bid;
    private String kf_online;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doods_store);
        ButterKnife.bind(this);
        mcontext = GoodsStoreActivity.this;
        storeid = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_STORE_ID);
        initTitle(0, "店铺详情");
        initUI();
        GetData(storeid);
        bid = storeid;
        GetListData(page, "?bid=" + storeid);
    }

    private void initUI() {
        head = getLayoutInflater().inflate(R.layout.activity_doods_store_head, null);
        store_collect = (TextView) head.findViewById(R.id.store_collect);
        list_coupon = (NestFullListView) head.findViewById(R.id.list_coupon);
        store_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (LoginState.getInstance().isLogin(mcontext)) {
                    CollectStore(storeid);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
            }
        });
        adapter = new MainlistAdapt(mcontext, null, "0");
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        adapter.addHeaderView(head);
        GridLayoutManager mGridLayoutManager = new GridLayoutManager(mcontext, 2);
        mRecyclerView.setLayoutManager(mGridLayoutManager);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
            }
        });

        initTab(tj_list);
        ReFreshData();
    }

    /**
     * 刷新
     */
    private void ReFreshData() {
        mRefreshLayout.setColorSchemeResources(R.color.app_title);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                if (networkConnected) {
                    page = 1;
                    GetData(storeid);
                    GetListData(page, "?bid=" + storeid);
                } else {
                    ObjectUtils.toast(mcontext, "网络连接出现异常");
                    mRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    /**
     * 店铺推荐
     *
     * @param tj_list
     */
    private void initTab(final List<StoreMessage.DataBean.CouponBean> tj_list) {
        list_coupon.setAdapter(new NestFullListViewAdapter<StoreMessage.DataBean.CouponBean>(R.layout.item_grid_store_coupon, tj_list) {
            @Override
            public void onBind(int position, StoreMessage.DataBean.CouponBean testBean, NestFullViewHolder holder) {
                if (testBean.getIs_has().equals("0")) {
                    holder.setBackgroundRes(R.id.coupon_bg_right, R.mipmap.store_coupon_red_right);
                    holder.setBackgroundRes(R.id.coupon_bg_left, R.mipmap.store_coupon_red_left);
                    holder.setText(R.id.coupon_bg_right, "领取");
                } else {
                    holder.setBackgroundRes(R.id.coupon_bg_right, R.mipmap.store_coupon_gray_right);
                    holder.setBackgroundRes(R.id.coupon_bg_left, R.mipmap.store_coupon_gray_left);
                    holder.setText(R.id.coupon_bg_right, "已领");
                }
                holder.setText(R.id.coupon_tv1, testBean.getAmount());
                if (testBean.getNeed_amount().equals("0")) {
                    holder.setText(R.id.coupon_tv2, "全场通用");
                } else {
                    holder.setText(R.id.coupon_tv2, "满" + testBean.getNeed_amount() + "元立减");
                }
                String end = ObjectUtils.getStrTime(testBean.getEnd_time(), "yyyy-MM-dd");
                if (testBean.getEnd_time().equals("0")) {
                    holder.setText(R.id.coupon_tv3, "有效期不限");
                } else {
                    holder.setText(R.id.coupon_tv3, "有限期至" + end);
                }
            }
        });

        list_coupon.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
            @Override
            public void onItemClick(NestFullListView nestFullListView, View view, int pos) {
                if (LoginState.getInstance().isLogin(mcontext)) {
                    getcoupon(tj_list.get(pos).getId(), view);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
            }
        });
    }

    private void GetData(String id) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERCOLLECTSTOREMESSAGE + "?bid=" + id;
        MyLog.e("地址", "" + address);
        if (networkConnected) {
            HttpUtils.get(address, null, new StoreMessageCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(StoreMessage response, int id) {
                    if (response == null) {
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0 && response.getData() != null) {
                        StoreMessage.DataBean data = response.getData();
                        kf_online = data.getKf_online();
                        StoreMessage.DataBean.BusinessBean business = data.getBusiness();
                        if (business != null) {
                            ((TextView) head.findViewById(R.id.store_name)).setText(business.getName());
                            ((TextView) head.findViewById(R.id.store_sell)).setText("销量：" + business.getSell_total());
                            ObjectUtils.photo(mcontext, business.getLogo(), (ImageView) head.findViewById(R.id.store_logo));
                            ImageView headImgView = (ImageView) head.findViewById(R.id.store_ad_img);
                            List<String> ad = business.getAd();
                            if(ObjectUtils.listHasData(ad)){
                                ObjectUtils.photo(mcontext, ad.get(0),  headImgView);
                            }else {
                                headImgView.setVisibility(View.GONE);
                            }
                        }
                        ((TextView) head.findViewById(R.id.store_goods)).setText("全部商品(" + data.getGoods_total() + ")");
                        if (LoginState.getInstance().isLogin(mcontext)) {
                            if (data.isIs_fav()) {
                                store_collect.setBackgroundResource(R.mipmap.detail_collect_store);
                                store_collect.setText("已关注");
                            } else {
                                store_collect.setBackgroundResource(R.mipmap.detail_uncollect_store);
                                store_collect.setText("关注店铺");
                            }
                        } else {
                            store_collect.setBackgroundResource(R.mipmap.detail_uncollect_store);
                            store_collect.setText("关注店铺");
                        }
                        //优惠券
                        tj_list.clear();
                        List<StoreMessage.DataBean.CouponBean> coupon = data.getCoupon();
                        if (ObjectUtils.listHasData(coupon)) {
                            tj_list.addAll(coupon);
                            list_coupon.updateUI();
                            (head.findViewById(R.id.store_coupon_nodata)).setVisibility(View.GONE);
                        }
                    } else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setVisibility(View.VISIBLE);
                        noDataTv.setText(response.getMsg());
                    }
                }
            });
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "网络未连接");
        }
    }

    private void CollectStore(String id) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.MEMBERCOLLECTSTOREACTION + "?bid=" + id;
            progressLoading.setVisibility(View.VISIBLE);
            String getid = LoginState.getInstance().getid(this);
            String getpd = LoginState.getInstance().getpd(this);
            HashMap<String, String> header = new HashMap<>();
            header.put("UID", getid);
            header.put("UPSW", getpd);
            HttpUtils.get(address, header, null, new dataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    progressLoading.setVisibility(View.GONE);
                }

                @Override
                public void onResponse(data response, int id) {
                    progressLoading.setVisibility(View.GONE);
                    if (response == null) {
                        return;
                    }
                    if (response.getCode() == 0) {
                        if (response.getMsg().equals("关注成功")) {
                            store_collect.setBackgroundResource(R.mipmap.detail_collect_store);
                            store_collect.setText("已关注");
                        } else if (response.getMsg().equals("取消成功")) {
                            store_collect.setBackgroundResource(R.mipmap.detail_uncollect_store);
                            store_collect.setText("关注店铺");
                        }
                    } else {
                        ObjectUtils.toast(mcontext, response.getMsg());
                    }
                }
            });
        } else {
            ObjectUtils.toast(mcontext, "网络未连接");
        }
    }

    private void getcoupon(String id, final View view) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.MEMBERCOLLECTSTOREGETYOUHUIQUAN + "?id=" + id;
            progressLoading.setVisibility(View.VISIBLE);
            String getid = LoginState.getInstance().getid(mcontext);
            String getpd = LoginState.getInstance().getpd(mcontext);
            HashMap<String, String> header = new HashMap<>();
            header.put("UID", getid);
            header.put("UPSW", getpd);
            HttpUtils.get(address, header, null, new dataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    progressLoading.setVisibility(View.GONE);
                }

                @Override
                public void onResponse(data response, int id) {
                    if (response == null) {
                        return;
                    }
                    progressLoading.setVisibility(View.GONE);
                    String msg = response.getMsg();
                    if (!TextUtils.isEmpty(msg)) {
                        ObjectUtils.toast(mcontext, msg);
                        if (msg.equals("领取成功")) {
                            view.findViewById(R.id.coupon_bg_right).setBackgroundResource(R.mipmap.store_coupon_gray_right);
                            view.findViewById(R.id.coupon_bg_left).setBackgroundResource(R.mipmap.store_coupon_gray_left);
                            ((TextView) view.findViewById(R.id.coupon_bg_right)).setText("已领");
                        }
                    }
                }
            });
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    //获取列表数据
    private void GetListData(final int page, String type) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.MEMBERCOLLECTSTOREGOODS + type + "&page=" + page;
            MyLog.e("地址", "" + address);
            HttpUtils.get(address, null, new StoreGoodCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {

                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(StoreGood response, int id) {
                    mRefreshLayout.setRefreshing(false);
                    if (response == null) {
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        StoreGood.DataBean data = response.getData();
                        if (data == null || !ObjectUtils.listHasData(data.getList())) {
                            adapter.loadMoreEnd();
                            return;
                        }
                        ArrayList<MainList.MainListdata.Mainlistdata> mListdata = new ArrayList<>();
                        List<StoreGood.DataBean.ListBean> list = data.getList();
                        for (int i = 0; i < list.size(); i++) {
                            StoreGood.DataBean.ListBean listBean = list.get(i);
                            mListdata.add(new MainList.MainListdata.Mainlistdata(1, listBean.getId()
                                    , listBean.getTypeid(), listBean.getName(), listBean.getPrice(), listBean.getTeam_price(), listBean.getDiscount_price()
                                    , listBean.getThumb(), listBean.getTeam_num(), listBean.getTeam_people_num(), listBean.getLuck_num(), listBean.getEnd_time()
                                    , listBean.getStart_time(), listBean.getRun_time()));
                        }
                        if (page == 1) {
                            adapter.setNewData(mListdata);
                        } else {
                            adapter.addData(mListdata);
                            adapter.loadMoreComplete();
                        }
                    } else {
                        adapter.loadMoreFail();
                        ObjectUtils.toast(mcontext, response.getMsg());
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }

    @OnClick({R.id.store_detail, R.id.store_contact, R.id.click_resetnetwork_refresh})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.store_detail:
                Intent intent = new Intent(mcontext, BaseObject.class);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "店铺详情");
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, storeid);
                startActivity(intent);
                // startActivityForResult(intent,1);
                break;
            case R.id.store_contact:
                Intent intents = new Intent(mcontext, BaseObject.class);
                intents.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "客服");
                if (TextUtils.isEmpty(kf_online)) {
                    if (bid != null && !bid.equals("")) {
                        intents.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_WEB_URL, ConstantsUrl.baseDomain + "chat?bid=" + bid);
                    } else {
                        intents.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_WEB_URL, ConstantsUrl.baseDomain + "chat");
                    }
                } else {
                    intents.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_WEB_URL, kf_online);
                }
                startActivity(intents);
                break;
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                GetData(storeid);
                GetListData(page, "?bid=" + storeid);
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetListData(page, "?bid=" + storeid);
    }
}